package org.yjc.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import org.yjc.repository.BookRepository;

import org.yjc.entity.Book;

@Service
public class BookService {
	@Autowired
	private BookRepository bookDAO;
	private String path = "e:/java/book"; //存文件路径

	public Book findById(Integer id) {
		Optional<Book> optional = bookDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	//事务处理, 上传
	@Transactional
	public void save(MultipartFile file, Book book) {
		//获取客户端上传文件名
		String filename = file.getOriginalFilename();
		//随机生成一个UUID
		String uuid = UUID.randomUUID().toString();
		book.setFilename(filename);
		book.setUuid(uuid);
		bookDAO.save(book);
		File path = new File(this.path);
		if(!path.isDirectory()) {
			path.mkdir();
		}
		File saveFile = new File(path, uuid);
		try {
			file.transferTo(saveFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
	}
	
	public Page<Book> findAll(Specification<Book> spec, Pageable pageable) {
		return bookDAO.findAll(spec,pageable);
	}
	
	public void download(Integer id, HttpServletRequest request, HttpServletResponse response) {
		Book book = findById(id);
		String filename = book.getFilename();
		filename = getStr(request, filename);
		String uuid = book.getUuid();
		File file = new File(path, uuid);
		if(file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename );
				ServletOutputStream out = response.getOutputStream();
				byte[] buf=new byte[2048];
				int n=0;
				while((n=fis.read(buf))!=-1){
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;
		//仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表 *=utf-8'zh_cn'文件名.xx部分）
        String agent = request.getHeader("USER-AGENT");  
         try {
            	 if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
            		 //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
            		 //设置字符集
            		 downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
            	 }else{
            		 downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
            	 }
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
		}
        return downloadFileName;
	}
	public void deleteById(Integer id) {
		bookDAO.deleteById(id);
	}
	
	public void save(Book book) {
		bookDAO.save(book);
	}
	public List<Book> findAll() {
		return bookDAO.findAll();
	}
}
